package com.lizhi.note.controller;

import com.lizhi.note.config.provider.CustomUser;
import com.lizhi.note.dto.AppUserDTO;
import com.lizhi.note.dto.UpdatePasswordDTO;
import com.lizhi.note.payload.ResponseUtil;
import com.lizhi.note.service.AppUserService;
import com.lizhi.note.service.TokenBlackListCacheService;
import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/users")
public class AppUserController {
    private final AppUserService userService;

    @Autowired
    TokenBlackListCacheService tokenBlackListCacheService;

    public AppUserController(AppUserService userService) {
        this.userService = userService;
    }

    // 创建用户
    @PostMapping
    public ResponseEntity<?> createUser(@Valid @RequestBody AppUserDTO userDTO) {
        AppUserDTO createdUser = userService.createUser(userDTO);
        createdUser.setPassword(null);
        return ResponseUtil.success(createdUser);
    }

    // 获取所有用户
    @GetMapping
    public ResponseEntity<?> getAllUsers() {
        List<AppUserDTO> users = userService.getAllUsers();
        for (AppUserDTO user : users) {
            user.setPassword(null);
        }
        return ResponseUtil.success(users);
    }

    // 根据ID获取用户
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUserinfo() {

        CustomUser user = getCurrentUserDetail();
        return getUserById(user.getUserId());
    }

    // 根据ID获取用户
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id) {
        AppUserDTO user = userService.getUserById(id).orElseThrow(() -> new EntityNotFoundException("用户id不存在"));
        user.setPassword(null);
        return ResponseUtil.success(user);
    }

    // 更新用户
    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id,
                                        @Valid @RequestBody AppUserDTO userDTO) {
        AppUserDTO updatedUser = userService.updateUser(id, userDTO);
        updatedUser.setPassword(null);
        return ResponseUtil.success(updatedUser);
    }

    /**
     * 修改密码，更新当前用户的密码，只有当前用户修改当前用户密码，因此不需要传入userId。
     * 修改密码后，删除cookie，前端需要重新登录，同时将当前token加入到blacklist中
     * @param updatePasswordDTO
     * @param response
     * @return
     */
    @PatchMapping("/password")
    public ResponseEntity<?> updatePassword(@RequestBody UpdatePasswordDTO updatePasswordDTO,  HttpServletResponse response) {

        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        CustomUser user = (CustomUser) authentication.getPrincipal();
        String token = (String) authentication.getCredentials();
        tokenBlackListCacheService.putElement(token);

        // 删除 Cookie
        Cookie jwtCookie = new Cookie("token", "invalid");
        jwtCookie.setPath("/");                // 整个应用都可以访问
        jwtCookie.setHttpOnly(false);           // 防止XSS攻击
        jwtCookie.setSecure(false);             // 仅HTTPS传输（生产环境建议启用）
        jwtCookie.setMaxAge(1);     // 有效期1天（秒）
        jwtCookie.setDomain("192.168.1.6");
        // 添加Cookie到响应
        response.addCookie(jwtCookie);

        userService.updatePassword(user.getUserId(), updatePasswordDTO.getOldPassword(), updatePasswordDTO.getNewPassword());
        return ResponseUtil.success(null, "更新密码成功");
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseUtil.success(null, "删除成功");
    }

    public CustomUser getCurrentUserDetail(){
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        CustomUser user = (CustomUser) authentication.getPrincipal();
        return user;
    }
}
